/*
 * Copyright 2017 Zhihu Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zhihu.matisse.sample;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SampleActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_CHOOSE = 23;
    private static final int REQUEST_CODE_TAKE_PHOTO = 44;

    private UriAdapter mAdapter;
    private List<Uri> uris;
    private List<String> paths;
    private ArrayList<Item> selectItems;
    private ArrayList<File> selectFiles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.zhihu).setOnClickListener(this);
        findViewById(R.id.zhihu2_all).setOnClickListener(this);
        findViewById(R.id.dracula).setOnClickListener(this);
        findViewById(R.id.only_gif).setOnClickListener(this);
        findViewById(R.id.only_video).setOnClickListener(this);
        findViewById(R.id.take_photo).setOnClickListener(this);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter = new UriAdapter());

//        RxPermissions rxPermissions = new RxPermissions(this);
//        Disposable subscribe = rxPermissions.request(android.permission.READ_MEDIA_IMAGES)
//                .subscribe(granted -> {
//
//                });
    }

    // <editor-fold defaultstate="collapsed" desc="onClick">
    @SuppressLint("CheckResult")
    @Override
    public void onClick(final View v) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        startAction(v);
                    } else {
                        Toast.makeText(SampleActivity.this, R.string.permission_request_denied, Toast.LENGTH_LONG)
                                .show();
                    }
                }, Throwable::printStackTrace);
    }
    // </editor-fold>

    private void startAction(View v) {
        switch (v.getId()) {
            case R.id.zhihu:
                Matisse.from(SampleActivity.this)
                        .choose(MimeType.ofImage(), false)
                        .countable(true)
                        .capture(true)//是否能拍照,true时recyclerview第一个条目是相机图标，false时全是图片
                        .captureStrategy(new CaptureStrategy(
                                //图片是否存在与沙盒内；true表示存到沙盒内；false表示存在外部，
                                false,
                                //唯一标识，一点要和AndroidManifest.xml中标签FileProvider下的保持一致，（习惯做法：包名+provider）
                                "com.zhihu.matisse.sample.fileprovider",
                                //拍照后照片存储的直接上级文件夹名字,名字随便取；最终路径：
                                //"/storage/emulated/0/Android/data/com.zhihu.matisse.sample/files/Pictures/myZhiHu/1632887606925.jpg"
                                "myZhiHu"/*"abc"*/))
                        .maxSelectable(9)
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .addFilter(new Filter() {
                            @Override
                            protected Set<MimeType> constraintTypes() {
                                return new HashSet<>();
                            }

                            @Override
                            public IncapableCause filter(Context context, Item item) {
                                if (!needFiltering(context, item))
                                    return null;
                                Uri uri = item.uri;
                                if(uris != null && uris.size() > 0 && uris.contains(uri)){
                                    return new IncapableCause(IncapableCause.TOAST, "图片已被选择");
                                }
                                return null;
                            }

                            @Override
                            public IncapableCause filter(Context context, File item) {
                                return null;
                            }
                        })
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .setOnSelectedListener((uriList, pathList) -> {
                            Log.e("onSelected", "onSelected: pathList=" + pathList);
                        })
                        .showSingleMediaType(true)
                        .originalEnable(true)
                        .maxOriginalSize(10)
                        .autoHideToolbarOnSingleTap(true)
                        .setOnCheckedListener(isChecked -> {
                            Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                        })
                        .defaultPath(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+"/myZhiHu")//设置为私有目录
                        .selectFiles(selectFiles)
                        .isUseMedia(false)
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.zhihu2_all:
                Matisse.from(SampleActivity.this)
                        .choose(MimeType.ofImage(), false)
                        .theme(R.style.Matisse_Zhihu)
                        .countable(true)
                        .capture(true)
                        .captureStrategy(new CaptureStrategy(
                                //图片是否存在与沙盒内；true表示存到沙盒内；false表示存在外部，
                                true,
                                //唯一标识，一点要和AndroidManifest.xml中标签FileProvider下的保持一致，（习惯做法：包名+provider）
                                "com.zhihu.matisse.sample.fileprovider",
                                //拍照后照片存储的直接上级文件夹名字,名字随便取；最终路径："Pictures/myZhiHu/1632887606925.jpg"
                                "myZhiHu"/*"abc"*/))
                        .maxSelectable(9)
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .setOnSelectedListener((uriList, pathList) -> {
                            Log.e("onSelected", "onSelected: pathList=" + pathList);
                        })
                        .showSingleMediaType(true)//true表示不能同时显示图片和视频
                        .originalEnable(true)
                        .maxOriginalSize(10)
                        .autoHideToolbarOnSingleTap(true)
                        .setOnCheckedListener(isChecked -> {
                            Log.e("isChecked", "onCheck: isChecked=" + isChecked);
                        })
                        .defaultPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                                .getAbsolutePath()+"/myZhiHu")//设置默认打开照片的路径,null表示展示全部的照片
//                        .defaultPath(null)
                        .choiceEnable(true)//true表示可以选择图集
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.dracula:
                Matisse.from(SampleActivity.this)
                        .choose(MimeType.ofAll())
                        .theme(R.style.Matisse_Dracula)
                        .countable(false)
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .maxSelectable(9)
                        .originalEnable(true)
                        .maxOriginalSize(10)
                        .showSingleMediaType(false)//默认false,表示可以同时显示图片和视频
                        .imageEngine(new GlideEngine())
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.only_gif:
                Matisse.from(SampleActivity.this)
                        .choose(MimeType.ofGif(), false)
                        .countable(true)
                        .maxSelectable(9)
                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                        .gridExpectedSize(
                                getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .showSingleMediaType(true)
                        .originalEnable(true)
                        .maxOriginalSize(10)
                        .autoHideToolbarOnSingleTap(true)
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.only_video:
                Matisse.from(SampleActivity.this)
                        .choose(MimeType.ofVideo())
                        .countable(true)
                        .maxSelectable(9)
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                        .thumbnailScale(0.85f)
                        .imageEngine(new GlideEngine())
                        .showSingleMediaType(true)
                        .originalEnable(false)
                        .autoHideToolbarOnSingleTap(true)
                        .forResult(REQUEST_CODE_CHOOSE);
                break;
            case R.id.take_photo://这就是直接拍照的功能
                Matisse.from(SampleActivity.this)
                        .choose(MimeType.of(MimeType.JPEG, MimeType.PNG))
                        .takePic(true)//设置立即拍照，跳转到系统相机界面
                        .capture(true)//设置是否可以拍照，并初始化数据
                        .captureStrategy(
                                new CaptureStrategy(
                                        //图片是否存在与沙盒内；true表示存到沙盒内；false表示存在外部，
                                        true,
                                        //唯一标识，一点要和AndroidManifest.xml中标签FileProvider下的保持一致，（习惯做法：包名+provider）
                                        "com.zhihu.matisse.sample.fileprovider",
                                        //拍照后照片存储的直接上级文件夹名字,名字随便取；最终路径："Pictures/myZhiHu/1632887606925.jpg"
                                        "myZhiHu"))
                        .forResult(REQUEST_CODE_TAKE_PHOTO);
                break;
            default:
                break;
        }
        mAdapter.setData(null, null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        System.out.println("-------->"+requestCode+"===="+resultCode+"-----"+data);
        if (resultCode == RESULT_OK) {
            uris = Matisse.obtainResult(data);
            paths = Matisse.obtainPathResult(data);
            selectItems = Matisse.obtainSelected(data);
            selectFiles = Matisse.obtainSelectedFile(data);
            Log.d("items----->", "onActivityResult  uris: "+uris);
            Log.d("items----->", "onActivityResult  paths: "+paths);
            Log.d("items----->", "onActivityResult  selectItems: "+selectItems);
            Log.d("items----->", "onActivityResult  selectFiles: "+selectFiles);
            mAdapter.setData(uris, paths);
//            Log.e("OnActivityResult ", String.valueOf(Matisse.obtainOriginalState(data)));
        }
    }

    private static class UriAdapter extends RecyclerView.Adapter<UriAdapter.UriViewHolder> {

        private List<Uri> mUris;
        private List<String> mPaths;

        void setData(List<Uri> uris, List<String> paths) {
            mUris = uris;
            mPaths = paths;
            notifyDataSetChanged();
        }

        @Override
        public UriViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new UriViewHolder(
                    LayoutInflater.from(parent.getContext()).inflate(R.layout.uri_item, parent, false));
        }

        @Override
        public void onBindViewHolder(UriViewHolder holder, int position) {
            holder.mUri.setText(mUris == null || mUris.get(position) == null? "": mUris.get(position).toString());
            holder.mPath.setText(mPaths.get(position));

            holder.mUri.setAlpha(position % 2 == 0 ? 1.0f : 0.54f);
            holder.mPath.setAlpha(position % 2 == 0 ? 1.0f : 0.54f);
        }

        @Override
        public int getItemCount() {
            return mPaths == null ? 0 : mPaths.size();
        }

        static class UriViewHolder extends RecyclerView.ViewHolder {

            private TextView mUri;
            private TextView mPath;

            UriViewHolder(View contentView) {
                super(contentView);
                mUri = (TextView) contentView.findViewById(R.id.uri);
                mPath = (TextView) contentView.findViewById(R.id.path);
            }
        }
    }

}
